<?

class mail
{
	protected $to;
	protected $subject;
	protected $message;
	protected $headers = array(
		'Content-type' => 'text/plain; charset=UTF-8'
	);
	
	protected $layout = 'mail';

	public function __construct( $to, $subject, $message )
	{
		$this->to = $to;
		$this->subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
		$this->message = $message;

		$from = config::get('mail_from') ? config::get('mail_from') : 'Support';
		$this->set_header('From', $from);
	}
	
	public function set_to( $to )
	{
		$this->to = $to;
	}

	public function set_header($name, $value)
	{
		$this->headers[$name] = $value;
	}

	public function send( $params = array() )
	{
		if ( $params['html'] || config::get('email_html') )
		{
			if ( $params['layout'] ) $this->layout = 'mail.' . $params['layout'];
			$params['message'] = $this->message;
			$this->message = render_html::render_template( render_html::get_layout_path($this->layout), $params);
			
			if ( $this->message )
			{
				$this->set_header('MIME-Version', '1.0');
				$this->set_header('Content-type', 'text/html; charset=UTF-8');
			}
		}

		if ( $from = $this->headers['From'] )
		{
			if ( $ltpos = mb_strpos($from, '<') )
			{
				$from_name = mb_substr($from, 0, $ltpos);
				$from_email = trim(mb_substr($from, $ltpos), '<>');

				$from = '=?UTF-8?B?' . base64_encode($from_name) . '?= <' . $from_email . '>';
			}

			$this->headers['From'] = $from;
		}

		foreach ( $this->headers as $k => $v ) $hlines[] = "{$k}: {$v}";

		$headers = implode("\r\n", $hlines);

		if ( $params['rapi'] )
		{
			$q = serialize(array(
				'to' => $this->to,
				'subject' => $this->subject,
				'message' => $this->message,
				'headers' => $this->headers,
			));
			
			$c = curl_init($params['rapi']);
			curl_setopt($c, CURLOPT_POST, true);
			curl_setopt($c, CURLOPT_POSTFIELDS, array('q' => $q));
			curl_setopt($c, CURLOPT_TIMEOUT, 1);
			curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
			curl_exec($c);
		}
		else if ( $queue = config::get('mail_queue') )
			gearman::do_background ($queue, array(
				'to' => $this->to,
				'subject' => $this->subject,
				'message' => $this->message,
				'headers' => $headers,
			), (bool)$params['important']);
		else
			mail($this->to, $this->subject, $this->message, $headers);

		if ( config::get('debug') )
		{
			file_put_contents('/Users/golotyuk/Desktop/mail.html', '<h1>' . base64_decode(str_replace(array('=?UTF-8?B?', '?='), '', $this->subject)) . '</h1><br /><br />' . $this->message);
			error_log(print_r($this->headers, 1));
		}
	}
}